<template>
  <div class="register-terminal-dialog">

    <el-dialog
      v-model="dialogVisible"
      title="精细招商注册终端"
      width="1050px"
      :before-close="handleClose"
    >

      <item-title title="精细招商要素基本信息"/>

      <el-form label-width="150px" size="small">
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品信息:">
<!--              {{ agentProduct.agentProductNumber }}-->
              {{getProductName(agentProduct)}}
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="招商要素编号:">-->
<!--              {{ agentProduct.agentProductNumber }}-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="产品通用名:">-->
<!--              {{ agentProduct.productPopularName }}-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="商品名:">-->
<!--              {{ agentProduct.productName }}-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="包装规格:">-->
<!--              {{ agentProduct.packSpecs }}-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="代理属性:">-->
<!--              <span v-if="agentProduct.agentAttribute == 1">独家招商</span>-->
<!--              <span v-if="agentProduct.agentAttribute == 2">精细招商</span>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

          <el-col :span="8">
            <el-form-item label="代理地区:">
              <area-list-view :areas="agentProduct.region" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交易价:">
              {{ agentProduct.tradePrice }}元/{{ getLabel('sell_unit',agentProduct.sellUnit) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="可营销终端:">
              {{ getLabel('app_mode',agentProduct.terminalType) }}
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <el-form
        ref="ruleForm"
        :rules="rules"
        :model="formData"
        size="small"
        label-width="150px"
      >
        <el-form-item
          label="负责营销职员"
          prop="headId"
        >
          <el-select
            v-model="formData.headId"
            placeholder="请选择营销职员"
            @change="headChange"
          >
            <el-option
              v-for="item in headOptions"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

<!--        <el-form-item label="注册终端列表">-->
<!--          <div>-->
<!--            <div>-->
<!--              <el-radio-group-->
<!--                v-model="radio"-->
<!--                :disabled="tableData.length > 0"-->
<!--              >-->
<!--                <el-radio :label="1">添加招商规划终端</el-radio>-->
<!--                <el-radio :label="2">添加非招商规划终端</el-radio>-->
<!--              </el-radio-group>-->

<!--            </div>-->
<!--          </div>-->
<!--        </el-form-item>-->

      </el-form>

      <item-title title="注册开发终端信息"/>

      <div style="display: flex;justify-content: space-between">
        <el-radio-group v-model="radio">
          <el-radio :label="1">添加营销任务终端</el-radio>
          <el-radio :label="2">添加未规划终端</el-radio>
        </el-radio-group>
        <div style="margin-bottom: 20px">
          <el-button
                  class="main-btn"
                  size="small"
                  type="primary"
                  @click="terminalClick"
          >添加终端</el-button>

          <el-button
                  class="main-btn"
                  size="small"
                  type="primary"
                  @click="allRemoved"
          >全部移除</el-button>
        </div>
      </div>

      <div>

        <el-table
          max-height="350px"
          border
          header-cell-class-name="table-header"
          :data="tableData"
          size="small"
        >
          <el-table-column
            header-align="center"
            align="left"
            label="终端名称"
            width="150px"
            show-overflow-tooltip
          >
            <template #default="scope">

              <el-popover
                v-if="scope.row.errorStatus || scope.row.isRepeat"
                placement="top-start"
                :width="200"
                trigger="hover"
              >
                <span v-if="scope.row.errorStatus">{{ errMap[scope.row.errorStatus] }}</span>
                <span v-else>终端已添加</span>

                <template #reference>
                  <el-icon style="margin-left: 10px">
                    <info-filled />
                  </el-icon>
                </template>
              </el-popover>

              <span>{{ scope.row.terminalName }}</span>

            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="所在地区"
            prop="area"
            width="100px"
            show-overflow-tooltip
          />
          <el-table-column
            header-align="center"
            align="center"
            label="准入模式"
            width="100px"
          >
            <template #default="scope">
              {{ getLabel('access_mode',scope.row.accessMode) }}
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="终端价(元)"
            width="100px"
          >
            <template #default="scope">
              {{ scope.row.terminalPrice }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="agentProduct.agentAttribute == 2"
            header-align="center"
            align="center"
            label="开发期限至"
            width="100px"
          >
            <template #default="scope">
              <span v-if="scope.row.expireTime">{{ dateFormat('yyyy-mm-dd',scope.row.expireTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="agentProduct.agentAttribute == 2"
            header-align="center"
            align="center"
            label="开发保证金(元)"
            width="150px"
          >
            <template #default="scope">
              <span v-if="scope.row.devEarnestMoney">{{ scope.row.devEarnestMoney }}</span>
              <span v-else>未设置</span>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="最低销量"
            width="150px"
          >
            <template #default="scope">
              <span v-if="scope.row.minSale">{{ scope.row.minSale }}{{ getLabel('sell_unit',agentProduct.sellUnit) }}/{{ getLabel('sell_num_unit',scope.row.minSaleUnit) }}</span>
              <span v-else>未设置</span>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="销量保证金(元)"
            width="150px"
          ><template
              #default="scope"
              width="100px"
            >
              <span v-if="scope.row.sellEarnestMoney">{{ scope.row.sellEarnestMoney }}</span>
              <span v-else>未设置</span>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="left"
            label="关联招商规划"
            prop="planName"
            width="150px"
            show-overflow-tooltip
          />
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            label="操作"
            width="150px"
          >
            <template #default="scope">
                {{scope.row.type}}
              <el-button
                v-if="scope.row.type == 1"
                type="text"
                @click.stop="onEdit(scope)"
              >编辑</el-button>
              <el-button
                type="text"
                @click.stop="onRemoved(scope)"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button  size="small" @click="handleClose">取消</el-button>
          <el-button
            type="primary"  size="small"
            @click="dialogConfirm"
          >提交审核</el-button>
        </div>
      </template>
    </el-dialog>

    <add-plan-termina-dialog
      ref="terminaDialog"
      :agent-product="agentProduct"
      :area="area"
      :list="tableData"
      @confirm="appConfirm"
    />

    <add-terminal-dialog
      :id="agentProduct.id"
      ref="appDialog"
      title="添加未规划终端"
      :unit="agentProduct.sellUnit"
      :props-product="agentProduct"
      is-product-price
      :list="tableData"
      mode="agent"
      :is-deadlin="agentProduct.agentAttribute == 2"
      @confirm="(data) => {appConfirm([data],1)}"
    />

    <edit-termina-dialog
      ref="editDialog"
      :unit="agentProduct.sellUnit"
      :props-product="agentProduct"
      is-product-price
      :is-deadlin="agentProduct.agentAttribute == 2"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import {crmStore} from "../../../store";
import {InfoFilled} from '@element-plus/icons'
import {getScreenAreaData} from '@/utils/areaFuc'
import {defineComponent, defineAsyncComponent, getCurrentInstance, inject, onBeforeMount, reactive, ref, toRefs,} from 'vue'

export default defineComponent({
  name: 'RegisterTerminalDialog',
  components: {
      InfoFilled,
      editTerminaDialog : defineAsyncComponent(()=>import('./editTerminaDialog.vue'))
  },
  props: {
    agentProduct: {
      type: Object,
      default: {},
    },
    agent: {
      type: Object,
      default: {},
    },
    type: {
      type: String,
      default: 'agent',
    },
  },
  setup(props, { emit }) {
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const headOptions = ref(crmStore.getters['company/getHeadOptions'])
    const rules = ref({
      headId: [
        {
          required: true,
          message: '请选择营销职员',
          trigger: 'change',
        },
      ],
    })
    var data = reactive({
      formData: {
        headId: '',
        headName: '',
        agentProductId: props.agentProduct.id,
      },
      tableData: [],
      dialogVisible: false,
      radio: 1,
      radioDisabled: false,
      appDialog: null,
      terminaDialog: null,
      area: [],
      ruleForm: null,
      editDialog: null,
    })

    const dialogConfirm = () => {
      // let a = {
      //     agentProductId:props.agentProduct.id,
      //     headId:1,
      //     headName:'张三',
      // }
      // if (!data.formData.headId){
      //     currentInstance.proxy.customMessage({
      //         type: 'error',
      //         message: '请选择营销人员',
      //     })
      //     return
      // }
      if (!data.tableData.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请添加终端',
        })
        return
      }

      data.ruleForm.validate((val) => {
        if (val) {
          const a = { ...data.formData }
          a.agentProductId = props.agentProduct.id
          a.productId = props.agentProduct.productId
          // if (data.radio == 1){
          //     let ids = []
          //     data.tableData.forEach(item=>{
          //         ids.push(item.id)
          //     })
          //     a.ids = ids
          //     a.sellMode = props.type
          // }else {
          //
          // }

          data.tableData.forEach((item) => {
            if (!item.expireTime) {
              item.expireTime = null
            }
            item.sellMode = props.type
          })
          a.terminals = data.tableData

          api.signedAgent.AGENT_SET_TERMINAL(a).then((res) => {
            if (!res.code && res.data) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '提交成功',
              })

              // data.dialogVisible = false
              emit('success')
              handleClose()
            } else {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            }
          })
        }
      })
    }

    const handleClose = () => {
      data.dialogVisible = false
      data.ruleForm.clearValidate()
      data.area = []

      setTimeout(() => {
        data.tableData = []
        data.formData.headId = ''
        data.formData.headName = ''
      }, 100)
    }

    const onRemoved = (scope) => {
      data.tableData.splice(scope.$index, 1)
    }

    const onEdit = (scope) => {
      data.editDialog.openDialog(scope.row)
    }

    const onConfirm = (val) => {
      const index = data.tableData.findIndex(
        (a) => a.terminalId == val.terminalId
      )
      if (index != -1) {
        data.tableData[index] = val
      }
    }

    const allRemoved = () => {
      data.tableData = []
    }

    const terminalClick = () => {
      if (data.radio == 1) {
        if (!data.area.length) {
          data.area = getScreenAreaData(props.agentProduct.region)
        }
        data.terminaDialog.openDialog()
      } else {
        data.appDialog.openDialog()
      }
    }

    const openDialog = () => {
      console.log(props.agentProduct)
      data.formData.headId = props.agentProduct.headId
      data.formData.headName = props.agentProduct.headName
      data.dialogVisible = true
    }

    const appConfirm = (list,type) => {
      const a = []
      let str = ''
      for (let i = 0; i < list.length; i++) {
        const index = data.tableData.findIndex(
          (a) => a.terminalId == list[i].terminalId
        )
        if (index == -1) {
          a.push(list[i])
        } else {
          if (str) {
            str = str + ','
          }
          str = str + list[i].terminalName
        }
      }

      if (str) {
        currentInstance.proxy.customMessage({
          type: 'warning',
          message: str + '已添加',
        })
      }

      if (type){
        a.type = type
      }
      data.tableData = data.tableData.concat(a)
    }

    const headChange = (val) => {
      if (val) {
        const index = headOptions.value.findIndex((a) => a.id === val)
        if (index !== -1) {
          data.formData.headName = headOptions.value[index].realName
        }
      } else {
        data.formData.headName = ''
      }
    }


    onBeforeMount(() => {

    })

    return {
      ...toRefs(data),
      headOptions,
      rules,

      handleClose,
      dialogConfirm,
      onRemoved,
      terminalClick,
      allRemoved,
      openDialog,
      appConfirm,
      headChange,
      onEdit,
      onConfirm,
    }
  },
})
</script>

<style scoped>
</style>
